package br.com.dev.tcc.util;

import br.com.dev.tcc.R;
import android.content.Context;
import android.widget.EditText;

public class CpfUtil {

	public static boolean isValid(Context context, EditText editText) {

		String cpf = editText.getText().toString().trim();

		if (cpf.length() != 11 || sameNumber(cpf) || !validDigits(cpf)) {

			editText.setCompoundDrawablesWithIntrinsicBounds(null, null,
					context.getResources().getDrawable(R.drawable.exclamation),
					null);
			return false;
		}

		editText.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);

		return true;
	}
	
	private static boolean sameNumber(String cpf){
		return cpf.matches("[0]{11}")
				|| cpf.matches("[1]{11}") || cpf.matches("[2]{11}")
				|| cpf.matches("[3]{11}") || cpf.matches("[4]{11}")
				|| cpf.matches("[5]{11}") || cpf.matches("[6]{11}")
				|| cpf.matches("[7]{11}") || cpf.matches("[8]{11}")
				|| cpf.matches("[9]{11}");
	}
	
	private static boolean validDigits(String cpf){
		
cpf = cpf.replace(".", "").replace("-", "");
		
		boolean isValid = false;
		
		int[] digits = new int[10];
		digits[0] = Character.getNumericValue(cpf.charAt(0));
		digits[1] = Character.getNumericValue(cpf.charAt(1));
		digits[2] = Character.getNumericValue(cpf.charAt(2));
		digits[3] = Character.getNumericValue(cpf.charAt(3));
		digits[4] = Character.getNumericValue(cpf.charAt(4));
		digits[5] = Character.getNumericValue(cpf.charAt(5));
		digits[6] = Character.getNumericValue(cpf.charAt(6));
		digits[7] = Character.getNumericValue(cpf.charAt(7));
		digits[8] = Character.getNumericValue(cpf.charAt(8));
		
		int index = 0;
		int sum = 0;
		for(int i = 10; i > 1; i--){
			sum += digits[index] * i;
			++index;
		}
		
		int first = sum % 11;
		if(first < 2) 
			first = 0;
		else
			first = 11 - first;
		
		isValid = first == Character.getNumericValue(cpf.charAt(9));
		
		if(isValid){
			
			digits[9] = first;
					
			sum = 0;
			index = 0;
			for(int i = 11; i > 1; i--){
				sum += digits[index] * i;
				++index;
			}
			
			int second = sum % 11;
			if(second < 2) 
				second = 0;
			else
				second = 11 - second;
			
			isValid = second == Character.getNumericValue(cpf.charAt(10));
		}
		
		return isValid;
	}

	public static String getFormattedCpf(String cpf) {

		if (cpf == null)
			return null;

		StringBuilder b = new StringBuilder();
		b.append(cpf.substring(0, 3));
		b.append(".");
		b.append(cpf.substring(3, 6));
		b.append(".");
		b.append(cpf.substring(6, 9));
		b.append("-");
		b.append(cpf.substring(9, 11));

		cpf = b.toString();
		return cpf;
	}
}
